package com.supervision.parent.ui.home;

import androidx.lifecycle.ViewModelProviders;

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.supervision.parent.R;
import com.supervision.parent.util.SaveNum;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AnnouncementFragment extends Fragment {

    private AnnouncementViewModel mViewModel;

    private String phone, webIp;
    LinearLayout llAnnStu, llAnnContent;
    List<JSONObject> jsonObjects = null;
    List<String> student = null;
    List<String> name = null;

    public static AnnouncementFragment newInstance() {
        return new AnnouncementFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.announcement_fragment, container, true);
        Map<String, String> userInfo = SaveNum.getUserInfo(getContext());
        if (userInfo != null) {
            phone = userInfo.get("phone");
            webIp = userInfo.get("webIp");
        }

        llAnnStu = root.findViewById(R.id.ll_ann_stu);
        llAnnContent = root.findViewById(R.id.ll_ann_content);
        llAnnStu.removeAllViews();
        llAnnContent.removeAllViews();


        GetAnnouncementAT getScheduleAT = new GetAnnouncementAT();
        getScheduleAT.execute(webIp, phone);
        return inflater.inflate(R.layout.announcement_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(AnnouncementViewModel.class);
        // TODO: Use the ViewModel
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        llAnnStu.removeAllViews();
        llAnnContent.removeAllViews();
    }

    class GetAnnouncementAT extends AsyncTask<String, String, String> implements View.OnClickListener {
        @Override
        protected String doInBackground(String... strings) {
            OkHttpClient okHttpClient = new OkHttpClient();//创建单例
            URL url;
            Request request;//创建请求
            String result = null;
            try {
                //设置url
                url = new URL("http://" + strings[0] + ":8080/getStudent/" + strings[1]);
                //设置请求
                request = new Request.Builder()
                        .url(url)
                        .build();
                //执行请求
                Response response = okHttpClient.newCall(request).execute();

                result = response.body().string();
                onProgressUpdate(result);
            } catch (Exception e) {
            }

            try {
                //设置url
                url = new URL("http://" + strings[0] + ":8080/getAnnouncement/" + strings[1]);
                //设置请求
                request = new Request.Builder()
                        .url(url)
                        .build();
                //执行请求
                Response response = okHttpClient.newCall(request).execute();

                result = response.body().string();
            } catch (Exception e) {
            }
            return result;
        }


        @Override
        protected void onProgressUpdate(String... values) {
            JSONArray jsonArray = null;
            student = new ArrayList<>();
            name = new ArrayList<>();

            try {
                jsonArray = new JSONArray(values[0]);
            } catch (JSONException e) {
            }
            JSONObject jsonObject = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    jsonObject = new JSONObject(jsonArray.get(i).toString());
                    student.add(jsonObject.optString("clazz"));
                    name.add(jsonObject.optString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        protected void onPostExecute(String s) {
            //初始化
            jsonObjects = new ArrayList<>();
            JSONArray jsonArray = null;
            try {
                jsonArray = new JSONArray(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    jsonObject = new JSONObject(jsonArray.get(i).toString());
                    jsonObjects.add(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            for (String str : student) {
                Button button = new Button(getContext());
                button.setText(name.get(student.indexOf(str)));
                button.setId(student.indexOf(str));
                button.setOnClickListener(this);
                llAnnStu.addView(button);
            }


        }

        @Override
        public void onClick(View v) {
            llAnnContent.removeAllViews();
            String clazz = student.get(v.getId());
            boolean isNull = true;
            for (JSONObject jsonObject : jsonObjects) {
                if (jsonObject.optString("clazz").equals(clazz)) {
                    TextView textView = new TextView(getContext());
                    textView.setText(jsonObject.optString("content"));
                    llAnnContent.addView(textView);
                    isNull = false;
                }
            }
            if (isNull == true) {
                TextView textView = new TextView(getContext());
                textView.setText("暂无公告");
                llAnnContent.addView(textView);
            }


        }
    }

}
